jQuery(document).ready(function($) {
	var ns = ns || {};
	ns.root = $('#server-path').val();
	ns.userid = $('#user-id').val();
	ns.pwdreg = /(?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{8,16})$/;
	ns.modalhref = '';
	ns.ppd = 0;

	ns.updateClock = function() {
		var now = new Date();
		var days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
		var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
		var hrs = now.getHours();
		if (hrs < 10) { hrs = '0'+hrs; }
		var mins = now.getMinutes();
		if (mins < 10) { mins = '0'+mins; }
		$('.main-header .time').html(hrs + ':' + mins);
		var date = now.getDate();
		if (date < 10) { date = '0'+date; }
		$('.main-header .date').html(days[now.getDay()]+', '+date+' '+months[now.getMonth()]+' '+now.getFullYear());
	};

	ns.initModal = function() {
		$('.modal button').click(function() {
			if ($(this).attr('id') === 'modal-confirm') {
				window.location = ns.modalhref;
			}
			ns.modalhref = '';
			$('.modal').hide();
		});
	};

	ns.modal = function(header, msg) {
		$('.modal .msg h2').html(header);
		$('.modal .msg p').html(msg);
		$('.modal').show();
	};

	ns.initDropDown = function() {
		$('.select').click(function(e) {
			if (!$(this).hasClass('disabled')) {
				e.stopPropagation();
				var span = $(this).find('span');
				var ul = $(this).find('ul');
				var input = $(this).find('input');
				ul.css('top', ($(this).height() * 0.5) - (ul.height() * 0.5));
				ul.show(100);
				$(document).click(function() {
					ul.hide(100);
					$(document).unbind('click');
				});
				ul.find('li').click(function(e) {
					e.stopPropagation();
					$(document).unbind('click');
					ul.find('li').unbind('click');
					ul.hide(100);
					span.html($(this).html());
					input.val($(this).attr('data-value'));
					input.trigger('change');
				});
			}
		});
	};

	ns.initCheckBox = function() {
		$('.checkbox').click(function(e) {
			e.stopPropagation();
			var input = $(this).find('input');
			if ($(this).hasClass('check')) {
				$(this).removeClass('check');
				input.val(0);
			} else {
				$(this).addClass('check');
				input.val(1);
			}
		});
	};

	ns.initFunctions = function() {
		$('.functions .delete').click(function(e) {
			e.preventDefault();
			ns.modalhref = e.currentTarget.href;
			ns.modal('Confirm Delete', 'Please note this action cannot be undone!');
		});

		$('.functions .subscribe').click(function(e) {
			e.preventDefault();
			ns.modalhref = e.currentTarget.href;
			ns.modal('Warning!', 'Are you sure you want to change subscription, this will cancel your current option and clear your free days.');
		});
	};
	
	ns.spaces = [];
	ns.space = [];
	ns.startTimeLi = null;
	ns.lastTimeLi = null;
	ns.minBlocks = 0;
	ns.maxBlocks = 0;
	ns.bookingBlocks = [];

	ns.initBooking = function() {
		ns.spaces = [];
		$('#building').change(function() {
			$('#occupants').val('1');
			$.post(ns.root+'php/spaces.php', {id: $(this).val()}, function(data) {
				ns.spaces = data;
				$('#spaces ul').empty();
				$('#spaces span').html('Select Space...');
				$('#spaces').removeClass('disabled');
				for (var i=0; i<data.length; i++) {
					$('#spaces ul').append('<li data-value="'+data[i].id+'">'+data[i].label+'</li>');
				}
			}, 'json');
		});
		$('#spaceid').change(function() {
			var arr = ns.searchArray($(this).val(), ns.spaces);
			ns.space = arr;
			ns.minBlocks = arr.mintime * 2;
			ns.maxBlocks = arr.maxtime * 2;
			$('label[for=occupants]').html('Occupants (1-'+arr.capacity+')');
			$('label[for=time]').html('Booking<br/>('+arr.mintime+' - '+arr.maxtime+' hours)');
			$('#occupants').autoNumeric('update', {aSep: '', vMin: '1', vMax: arr.capacity});
			$('#occupants').removeAttr('disabled');
			$('#date').removeAttr('disabled');
			$('#date').change();
		});

		$('#date').change(function() {
			var space = $('#spaceid').val(), date = $(this).val();
			ns.bookingBlocks = [];
			$.post(ns.root+'php/bookings.php', {id: space, date: date, type: 'booking'}, function(data) {
				$('.time li').removeClass('booked').removeClass('disabled');
				for (var i=0; i<data.length; i++) {
					var len = data[i].mins / 60;
					len = len / 0.5;
					var start = data[i].start;
					start = start.substring(11, 16);
					$('.time li:contains('+start+')').addClass('booked');
					var index = $('.time li:contains('+start+')').index();
					$('.time li').slice(index, index+len).addClass('disabled');
				}
				$('.time li').each(function() {
					var val = $(this).hasClass('disabled') ? -1 : 0;
					ns.bookingBlocks.push(val);
				});
				$('.cost .price').html('R0');
			}, 'json');
		});

		$('.time li:not(.disabled)').mousedown(function() {
			ns.clearBookings();

			$('body').addClass('noselect');

			ns.startTimeLi = parseInt($(this).attr('data-index'), 0);
			ns.lastTimeLi = parseInt($(this).attr('data-index'), 0);

			$('.time li').mouseover(function() {
				if (!$(this).hasClass('disabled') || !$(this).prev().hasClass('disabled')) {
					ns.lastTimeLi = parseInt($(this).attr('data-index'), 0);
					if (ns.lastTimeLi < ns.startTimeLi + ns.minBlocks - 1) { ns.lastTimeLi = ns.startTimeLi + ns.minBlocks - 1; }
					if (ns.lastTimeLi > ns.startTimeLi + ns.maxBlocks - 1) { ns.lastTimeLi = ns.startTimeLi + ns.maxBlocks - 1; }
					var bookingSize = 0;
					for (var i=ns.startTimeLi; i < ns.lastTimeLi + 1; i++) {
						if (ns.bookingBlocks[i] !== -1) {
							bookingSize++;
							$('.time li[data-index='+i+']').addClass('booked');
							ns.bookingBlocks[i] = 1;
						} else {
							if (bookingSize < ns.minBlocks) { ns.clearBookings(); }
							break;
						}
					}
					$('.time li:nth-child('+i+')').nextAll().removeClass('booked');
					$('.cost .price').html('R'+(ns.space.hourlyrate*(bookingSize/2)));
				}
			});

			$(this).mouseover();

			$('body').mouseup(function() {
				$('.time li').unbind('mouseover');
				$('body').removeClass('noselect');
				ns.startTimeLi = 0;
				ns.lastTimeLi = 0;
				$('#timeblock').val(ns.bookingBlocks);
			});
		});
	};

	ns.clearBookings = function() {
		$('.time li').removeClass('booked');
		for (var i=0; i<ns.bookingBlocks.length; i++) {
			if (ns.bookingBlocks[i] !== -1) { ns.bookingBlocks[i] = 0; }
		}
	};

	ns.searchArray = function(id, array) {
		for (var i=0; i<array.length; i++) {
			if (array[i].id === id) {
				return array[i];
			}
		}
	};

	ns.trainingData = [];
	ns.disabledDates = [];

	ns.initTrainingBooking = function() {
		$('form button').before('<label>&nbsp;</label><h4 class="cost">TOTAL COST OF BOOKING: <span class="price">R</span></h4>');
		$('#trainingid').change(function() {
			//$('#delegates').val('1');
			$.post(ns.root+'php/training.php', {id: $(this).val()}, function(data) {
				ns.trainingData = data[0];
				$('#delegates').spinner({
					min: ns.trainingData.mincapacity,
					max: ns.trainingData.maxcapacity,
					step: 1
				});
				$('#delegates').val(ns.trainingData.mincapacity);
				$('.cost .price').html('R'+(parseInt(ns.trainingData.price,0) * $('#delegates').val()));
			}, 'json');
		});
		$('#delegates').change(function(){
			if ($('#delegates').val() > ns.trainingData.maxcapacity) { $('#delegates').val(ns.trainingData.maxcapacity); }
			if ($('#delegates').val() < ns.trainingData.mincapacity) { $('#delegates').val(ns.trainingData.mincapacity); }
			$('.cost .price').html('R'+(parseInt(ns.trainingData.price,0) * $('#delegates').val()));
			console.log($('#delegates').val());
		});
		$('#trainingid').change();
		// get dates
		$.post(ns.root+'php/bookings.php', {id: 0, date: '', type: 'training'}, function(data) {
			ns.disabledDates = [];
			var arr = [];
			for (var i=0; i<data.length; i++) {
				arr = data[i].date.split('-');
				ns.disabledDates[i] = parseInt(arr[1],0)+'-'+parseInt(arr[2],0)+'-'+parseInt(arr[0],0);
			}
			$('.input-date-disabled').datepicker({
				currentText: 'now',
				dateFormat: 'yy-mm-dd',
				minDate: new Date(window.year+' '+window.month+' '+window.day),
				beforeShowDay: ns.noWeekendsOrBooked
			});

		}, 'json');
	};

	ns.getDisabled = function(date) {
		var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
		console.log('Checking (raw): ' + m + '-' + d + '-' + y);
		for (var i = 0; i < ns.disabledDates.length; i++) {
			if($.inArray((m+1) + '-' + d + '-' + y,ns.disabledDates) !== -1 || new Date() > date) {
				console.log('bad:  ' + (m+1) + '-' + d + '-' + y + ' / ' + ns.disabledDates[i]);
				return [false];
			}
		}
		console.log('good:  ' + (m+1) + '-' + d + '-' + y);
		return [true];
	};
	
	ns.noWeekendsOrBooked = function(date) {
		var noWeekend = jQuery.datepicker.noWeekends(date);
		return noWeekend[0] ? ns.getDisabled(date) : noWeekend;
	};

	ns.initCalendar = function() {
		$('#full-calendar').fullCalendar({
			defaultView: 'agendaWeek',
			firstHour: 7,
			minTime: 6,
			maxTime: 20,
			header: {
				left: 'prev,next today',
				center: 'title',
				right: 'month,agendaWeek,agendaDay'
			},
			editable: true,
			events: {
				allDayDefault: false,
				editable: false,
				url: 'php/events.php?id='+ns.userid
			}
		});
	};

	ns.initProgressScrubber = function() {
		$('.progress .scrubber').mousedown(function(e) {
			e.preventDefault();
			$('body').addClass('noselect');
			$(window).mousemove(function(e) {
				e.stopPropagation();
				var x = e.pageX - $('.progress').offset().left;
				if (x > $('.progress').width() - 18) { x = $('.progress').width() - 18; }
				if (x < 0) { x = 0; }
				var percentage = Math.round(x / ($('.progress').width()-18) * 100);
				$('.progress .scrubber').css('left', percentage+'%');
				$('.progress li:first-child').width(percentage+'%');
				$('.progress li:first-child').attr('data-percentage', percentage);
				var val = Math.round(x / ($('.progress').width()-18) * 365);
				if (val < 1) { val = 1; }
				$('#amount').val(val);
				$('.total').html('R'+(ns.ppd*val)+'.00');
				//console.log(e.pageX, e.pageY);
			}).mouseup(function() {
				$(this).unbind('mouseup');
				$(this).unbind('mousemove');
				$('body').removeClass('noselect');
			});
		});
	};

	ns.initAlerts = function() {
		setInterval(ns.updateAlerts, 30000);
		ns.updateAlerts();
	};

	ns.updateAlerts = function() {
		$.get(ns.root+'php/alerts.php', function(data) {
			$('.main-header .menu .count').html(data.length);
			if (data.length > 0) { $('.main-header .menu .count').show(0); }
			else { $('.main-header .menu .count').hide(0); }
		}, 'json');
	};

	// global init

	ns.init = function() {
		if ($('.select').length > 0) { ns.initDropDown(); }
		if ($('.checkbox').length > 0) { ns.initCheckBox(); }
		if ($('.functions').length > 0) { ns.initFunctions(); }
		if ($('.booking').length > 0) { ns.initBooking(); }
		if ($('#full-calendar').length > 0) { ns.initCalendar(); }
		if ($('.progress .scrubber').length > 0) { ns.initProgressScrubber(); }
		if ($('.main-header .menu .alerts').length > 0) { ns.initAlerts(); }
		if ($('#training-booking').length > 0) { ns.initTrainingBooking(); }

		$('.input-decimal').autoNumeric('init', {aSep: ''});
		$('.input-year').autoNumeric('init', {aSep: '', vMin: '1', vMax: '365'});
		$('.input-hours').autoNumeric('init', {aSep: '', vMin: '00', vMax: '17', lZero: 'keep'});
		$('.input-mins').autoNumeric('init', {aSep: '', vMin: '00', vMax: '59', lZero: 'keep'});
		$('.input-integer').autoNumeric('init', {aSep: '', mDec: '0'});
		$('.input-tel').autoNumeric('init', {aSep: '', mDec: '0', lZero: 'keep', vMax: '9999999999'});
		$('.input-time').autoNumeric('init', {aSep: '', aDec: ':', mDec: '2', lZero: 'keep', vMax: '23.59'});

		$('.list-table td:not(.functions)').click(function(e) {
			e.stopPropagation();
			if ($(this).parent().find('.functions .view').length > 0) {
				window.location = $(this).parent().find('.functions .view').attr('href');
			}
		});

		if ($('#subscription-id').length > 0) {
			var id = $('#subscription-id').val();
			$('tr[data-id='+id+']').find('.subscribe').replaceWith('<span class="noclick">Subscribed</span>');
		}

		$('.progress li').each(function() {
			$(this).animate({width: $(this).attr('data-percentage')+'%'}, 1000);
		});

		if ($('#ppd').length > 0) {
			ns.ppd = $('#ppd').val();
		}

		$('#amount').keyup(function() {
			var percentage = Math.round($(this).val() / 365 * 100);
			$('.progress .scrubber').animate({left:percentage+'%'}, 250);
			$('.progress li:first-child').animate({width:percentage+'%'}, 250);
			$('.progress li:first-child').attr('data-percentage', percentage);
			$('.total').html('R'+(ns.ppd*$('#amount').val())+'.00');
		});

		$('#PayGateSubmit').click(function() {
			$(this).parent().hide(0);
			$('#paygate_response').show(0);
		});

		$('.input-date').datepicker({
			currentText: 'now',
			dateFormat: 'yy-mm-dd',
			minDate: new Date(window.year+' '+window.month+' '+window.day),
			beforeShowDay: $.datepicker.noWeekends
		});

		$('.input-date').change(function() {
			ns.updateDateTime();
		});

		$('.input-hours').change(function() {
			if ($(this).val() < 10) {
				$(this).val('0'+$(this).val());
			}
			ns.updateDateTime();
		});

		$('.input-mins').change(function() {
			if ($(this).val() < 10) {
				$(this).val('0'+$(this).val());
			}
			ns.updateDateTime();
		});

		$('.list-table').tablesorter({
			cssAsc: 'sort-up',
			cssDesc: 'sort-down'
		});
		
		ns.updateClock();
		setInterval(ns.updateClock, 30000);

		var minHeight = 0;
		$('.main-nav').children().each(function() {
			minHeight += $(this).outerHeight();
		});
		//$('.main-nav').css('min-height', minHeight+'px');
		
		ns.initModal();
	};

	ns.updateDateTime = function() {
		$('#start').val($('.input-date').val() + ' ' + $('.input-hours').val() + ':' + $('.input-mins').val() + ':00');
	};

	ns.init();
});